//
//  EditeAppViewController.m
//  IconMaster
//
//  Created by mac on 2017/7/25.
//  Copyright © 2017年 yangweiwei. All rights reserved.
//

#import "EditeAppViewController.h"
#import "AppCollectionViewCell.h"
#import "HeaderCollectionView.h"
#import "FooterCollectionView.h"
#import "PopView.h"
#import "MongooseDaemon.h"
#import "RMStepsController.h"
#import "AppViewController.h"
static NSString * const headerIdentifier = @"header";

static NSString * const footerIdentifier = @"footer";
@interface EditeAppViewController ()<PopViewDelegate, HeaderCollectionViewDelegate, FooterCollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UIButton *moreAppBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *defalutAppArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger totalPages;
@end

@implementation EditeAppViewController
- (IBAction)moreBtnAction:(id)sender {
}
- (NSMutableArray *)defalutAppArr{

    if (!_defalutAppArr) {
        _defalutAppArr = [NSMutableArray array];
    }
    return _defalutAppArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setImageViewINNav];
    [self setBarType];
    [self readPlistFile:0];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];
//    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        
//        if (self.page > 0) {
//             [self readPlistFile:self.page--];
//        }  else{
//           [self.collectionView.mj_footer endRefreshing];
//        }
//    }];
 
    //appcollectioncell
    // Do any additional setup after loading the view.
}
- (void)readPlistFile:(NSInteger)inter{
    
    
    [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:IconList andparameters:@{@"page":@"0",@"size":@"100"} andcomplete:^(id json, NSError *error) {
        if ([json[@"code"] integerValue] == 200) {
            if (self.defalutAppArr != json[@"data"][@"list"][@"content"]) {
                [self.defalutAppArr addObjectsFromArray: json[@"data"][@"list"][@"content"]];
                self.totalPages = [json[@"data"][@"list"][@"totalPages"] integerValue];
            }
           
            [self.collectionView reloadData];
//            [self.collectionView.mj_footer endRefreshing];
        }
        
    }];
    
    
//    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"CusURLSheme" ofType:@"plist"];  
////    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];  
////    NSMutableArray *dataArr = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
//    NSArray *arr = [NSArray arrayWithContentsOfFile:plistPath];
//    self.defalutAppArr = arr;
    NSLog(@"%@", self.defalutAppArr );//直接打印数据。
}

#pragma mark ---UICollectionView DataSource

- (NSInteger)numberOfItemsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.defalutAppArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"appcollectioncell";
    AppCollectionViewCell *cell = (AppCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
//    NSString *imageStr = self.defalutAppArr[indexPath.row][@"image"];iconPath
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BaseURLImage, self.defalutAppArr[indexPath.row][@"iconPath"]]]];
//    cell.iconImageView.image = [UIImage imageNamed:self.defalutAppArr[indexPath.row][@"image"]];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.defalutAppArr[indexPath.row][@"appName"]];
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
[self showAdmobInController:self];
    PopView *popView = [[PopView alloc] initWithFrame:CGRectMake(0, 64, KWidth, KHeight - 64) withImage:self.customerImg withURLScheme:self.defalutAppArr[indexPath.row][@"urlScheme"]];
    popView.delegate = self;
//    popView.backgroundColor = [UIColor redColor];
    [self.view addSubview:popView];
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(KWidth, 50);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeMake(KWidth, 50);
}
// 为collection view添加页眉或页脚

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{
    HeaderCollectionView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
//    UICollectionReusableView *reusableview = nil;
//
//    if (kind == UICollectionElementKindSectionHeader){
//    HeaderCollectionView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
//        
//        headerView.delegate = self;
//        
//        reusableview = headerView;
//    }
    
//    else if (kind == UICollectionElementKindSectionFooter){
//        FooterCollectionView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier forIndexPath:indexPath];
//        
//         footerview.delegate = self;
//        
//         reusableview = footerview;
//    }
//    HeaderCollectionView *headerView = reusableHeaderView;
    return headerView;
}
- (void)popViewButton:(NSDictionary *)dict{

    NSLog(@"%@", dict);
    UIImage* iconImage = self.customerImg;
    SaveImageToDocument(iconImage, @"the_icon.png");
    
    NSString* title = [dict objectForKey:@"title"];
    
    NSString* value = [dict objectForKey:@"value"];
    
    [MongooseDaemon instance].composedUrl.title = title;
    [MongooseDaemon instance].composedUrl.password = nil;
    [MongooseDaemon instance].composedUrl.realUrl = value;
    
    NSString* urlString = [NSString stringWithFormat:@"http://localhost:8080/wei%ld",time(NULL)];
//    NSLog(@"%@",urlString);
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
//    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:value]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:^(BOOL success) {
            //
        }];
        [self.stepsController finishedAllSteps];
//    } else {
//        [self alterAction:@"您的手机没有安装该应用"];
//    }
    

}
- (void)headerButton:(NSDictionary *)dict{
//[self showAdmobInController:self];
    NSLog(@"%@", dict);
    if ([self matchingArrtitle:dict[@"title"]]) {
        //have
    }else{
    
        //
        [self alterAction:NSLocalizedString(@"该应用正在添加中，请耐心等待",nil)];
    }
}
- (void)footerViewButton{

    NSLog(@"更多");
    [self checkIOSInStore:^(NSInteger isbool) {
        if (isbool) {
            //    moreFeed
//            if (![DBOperation isAppListEnabled]) {
//                //        return;
//            }
            __weak typeof(self) wself = self;
            
            AppViewController* controller = [[AppViewController alloc] init];
            controller.cancelBlock = ^(AppViewController* ctl) {
                [wself hideAppView];
            };
            controller.appSelectedBlock = ^(AppViewController* ctl, NSDictionary* infoDict) {
                [wself setValueWithAppInfoDict:infoDict];
                [wself hideAppView];
            };
            
            UINavigationController* navigationController =[[UINavigationController alloc] initWithRootViewController:controller];
            navigationController.navigationBar.translucent = NO;
            [self presentViewController:navigationController
                               animated:YES
                             completion:nil];

        } else {
             [self performSegueWithIdentifier:@"moreFeed" sender:self];
        }
    }];
//
}
- (void)hideAppView
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)setValueWithAppInfoDict:(NSDictionary*)infoDict
{
    NSLog(@"%@", infoDict);
//    self.titleTextField.text = [infoDict objectForKey:APP_KEY_NAME];
//    
//    NSString* scheme = [infoDict objectForKey:APP_KEY_SCHEME];
//    scheme = NormalizeUrlScheme(scheme);
//    self.valueTextField.text = scheme;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)matchingArrtitle:(NSString *)string{

    BOOL isBool = '\0';
    for (NSDictionary *dict in self.defalutAppArr) {
        if ([string isEqualToString:dict[@"name"]]) {
            isBool = YES;
        }
    }
    return isBool;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
